import crypto from 'crypto';
import { HuifengPayService, HuifengPayConfig } from '../src/services/huifengPayService';

// 测试配置
const testConfig: HuifengPayConfig = {
  merchantId: '1335783598896247802',
  secretKey: process.env.HUIFENG_SECRET_KEY || 'your_secret_key',
  baseUrl: 'https://xhf-uat-api-pay.imbillls.com',
  notifyUrl: 'https://52.77.253.74:3017/api/callback/huifeng',
  collectionPayType: '90801',
  country: 'TH',
  defaultUserIp: '127.0.0.1',
  fallbackEmail: 'test@example.com',
  fallbackPhone: '+66123456789'
};

// 直接HTTP请求测试函数
async function testDirectRequest() {
  console.log('🌐 开始直接HTTP请求测试...\n');

  const orderId = `TEST${Date.now()}${Math.random().toString(36).substring(2, 8).toUpperCase()}`;

  // 生成签名的函数
  function generateSign(params: Record<string, any>, secretKey: string, excludeKeys: string[] = ['sign']): string {
    const filteredParams = Object.keys(params)
      .filter(key => !excludeKeys.includes(key) && params[key] !== undefined && params[key] !== '')
      .sort()
      .reduce((obj, key) => {
        obj[key] = params[key];
        return obj;
      }, {} as Record<string, any>);

    const paramString = Object.keys(filteredParams)
      .map(key => `${key}=${filteredParams[key]}`)
      .join('&');

    const signString = paramString + secretKey;
    console.log('🔐 签名原始字符串:', signString.replace(secretKey, '***SECRET***'));

    const sign = crypto.createHash('md5').update(signString).digest('hex').toUpperCase();
    console.log('🔐 生成签名:', sign);

    return sign;
  }

  const requestData = {
    merchantId: testConfig.merchantId,
    payType: testConfig.collectionPayType,
    orderId: orderId,
    amount: '1.00',
    notifyUrl: testConfig.notifyUrl,
    country: testConfig.country,
    userName: '测试用户',
    accNo: '1234567890123456',
    bankCode: '010',
    email: testConfig.fallbackEmail,
    phone: testConfig.fallbackPhone,
    user_ip: testConfig.defaultUserIp
  };

  // 生成签名
  (requestData as any).sign = generateSign(requestData, testConfig.secretKey);

  console.log('📋 请求参数:', {
    ...requestData,
    sign: '***'
  });

  // 测试网络连通性
  try {
    console.log('\n🔗 测试网络连通性...');
    const connectResponse = await fetch(testConfig.baseUrl, {
      method: 'GET',
      headers: {
        'User-Agent': 'TaiGuoChongZhiSystem/1.0'
      }
    });

    console.log('✅ 基础URL响应状态:', connectResponse.status);
    if (connectResponse.status !== 200) {
      const text = await connectResponse.text();
      console.log('📄 响应内容:', text.substring(0, 200) + '...');
    }
  } catch (error) {
    console.error('❌ 网络连通性测试失败:', (error as Error).message);
  }

  // 测试JSON格式请求
  try {
    console.log('\n📡 测试方法1: JSON格式请求...');
    const jsonResponse = await fetch(`${testConfig.baseUrl}/pay/collection/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'User-Agent': 'TaiGuoChongZhiSystem/1.0'
      },
      body: JSON.stringify(requestData)
    });

    console.log('📊 JSON响应状态:', jsonResponse.status);
    const jsonResult = await jsonResponse.text();
    console.log('📄 JSON响应内容:', jsonResult);

  } catch (error) {
    console.error('❌ JSON请求失败:', (error as Error).message);
  }

  // 测试Form格式请求
  try {
    console.log('\n📡 测试方法2: Form格式请求...');
    const formData = new URLSearchParams();
    Object.keys(requestData).forEach(key => {
      if ((requestData as any)[key] !== undefined && (requestData as any)[key] !== '') {
        formData.append(key, (requestData as any)[key].toString());
      }
    });

    const formResponse = await fetch(`${testConfig.baseUrl}/pay/collection/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'TaiGuoChongZhiSystem/1.0'
      },
      body: formData.toString()
    });

    console.log('📊 Form响应状态:', formResponse.status);
    const formResult = await formResponse.text();
    console.log('📄 Form响应内容:', formResult);

  } catch (error) {
    console.error('❌ Form请求失败:', (error as Error).message);
  }

  // 测试方法3: 尝试直接发送表单字符串
  try {
    console.log('\n📡 测试方法3: 手动构建Form字符串...');

    // 手动构建form字符串，确保数字类型正确
    const formPairs = Object.keys(requestData).map(key => {
      const value = (requestData as any)[key];
      // 对于数字字段，不使用引号
      if (key === 'merchantId' || key === 'payType') {
        return `${key}=${value}`;
      }
      return `${key}=${encodeURIComponent(value)}`;
    });
    const formString = formPairs.join('&');

    console.log('📋 手动Form字符串:', formString);

    const manualResponse = await fetch(`${testConfig.baseUrl}/pay/collection/create`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'TaiGuoChongZhiSystem/1.0'
      },
      body: formString
    });

    console.log('📊 手动Form响应状态:', manualResponse.status);
    const manualResult = await manualResponse.text();
    console.log('📄 手动Form响应内容:', manualResult);

  } catch (error) {
    console.error('❌ 手动Form请求失败:', (error as Error).message);
  }
}

// 测试HuifengPayService类
async function testHuifengPayService() {
  console.log('\n🧪 开始测试 HuifengPayService 类...\n');

  try {
    // 创建服务实例
    const huifengService = new HuifengPayService(testConfig);
    console.log('✅ HuifengPayService 实例创建成功');

    // 测试订单号生成
    const orderId = huifengService.generateOrderId();
    console.log(`✅ 订单号生成成功: ${orderId}`);

    // 测试创建代收订单
    console.log('\n💰 测试创建代收订单...');
    const orderRequest = {
      userId: 1231,
      amount: 1,
      paymentMethod: 'qrPay' as const,
      orderId: orderId,
      transAccNo: '1234567890123456',
      paymentName: '测试用户',
      bankCode: '010',
      customerEmail: 'test@example.com',
      customerPhone: '+66123456789'
    };

    const orderResponse = await huifengService.createRechargeOrder(orderRequest);
    console.log('✅ 代收订单创建响应:', orderResponse);

  } catch (error) {
    console.error('❌ HuifengPayService 测试失败:', error);
  }
}

// 主测试函数
async function main() {
  console.log('🚀 开始汇沣支付API测试\n');
  console.log('🔧 测试配置:');
  console.log(`   商户ID: ${testConfig.merchantId}`);
  console.log(`   API地址: ${testConfig.baseUrl}`);
  console.log(`   回调地址: ${testConfig.notifyUrl}`);
  console.log(`   支付类型: ${testConfig.collectionPayType}`);
  console.log(`   国家: ${testConfig.country}\n`);

  if (!testConfig.secretKey || testConfig.secretKey === 'your_secret_key') {
    console.error('❌ 错误: 请设置环境变量 HUIFENG_SECRET_KEY');
    console.log('💡 使用方法: HUIFENG_SECRET_KEY=你的密钥 bun run test:huifeng');
    process.exit(1);
  }

  try {
    await testDirectRequest();
    await testHuifengPayService();
    console.log('\n🎉 测试完成!');
  } catch (error) {
    console.error('\n💥 测试过程中发生错误:', error);
    process.exit(1);
  }
}

// 运行测试
if (require.main === module) {
  main().catch(console.error);
}